/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.application.login;

import com.lap.auth.application.login.assembler.LoginLogAssembler;
import com.lap.auth.application.login.command.CreateLoginLogCmd;
import com.lap.auth.application.login.dto.LoginLogDto;
import com.lap.auth.application.login.dto.QueryLoginLogPageQuery;
import com.lap.auth.application.login.repository.LoginLogQueryRepository;
import com.lap.auth.domain.login.LoginLog;
import com.lap.auth.domain.login.repository.LoginLogRepository;
import com.lap.auth.domain.user.repository.UserRepository;
import com.lap.auth.shared.ports.Ip2AddressService;
import com.lap.framework.common.dto.page.PageResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 登录日志应用服务层
 *
 * <ol>
 *   <li>不做业务规则，只做技术规则（加密/解密是技术实现，业务不关注）
 *   <li>取数，赋值，对象转换在这层执行
 *   <li>命名有规范，动词+领域名字
 *   <li>如查询比较多，建议分开领域QueryAppService,如:分页查询，分页查询返回关联字段
 * </ol>
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class LoginLogAppService {

  private final LoginLogAssembler loginLogAssembler;
  private final Ip2AddressService ip2AddressService;
  private final LoginLogRepository repository;
  private final LoginLogQueryRepository queryRepository;
  private final UserRepository userRepository;

  public PageResponse<LoginLogDto> queryLoginLogsByPage(QueryLoginLogPageQuery query) {
    return queryRepository.findByConditionPaged(query);
  }

  public void createLoginLog(CreateLoginLogCmd cmd) {
    LoginLog loginLog = loginLogAssembler.toDomain(cmd);
    setInfo(cmd, loginLog);
    repository.save(loginLog);
  }

  private void setInfo(CreateLoginLogCmd cmd, LoginLog loginLog) {
    userRepository
        .findByUserName(cmd.getUserName())
        .ifPresentOrElse(
            user -> loginLog.changeUserInfo(user.getId(), user.getFullName()),
            () -> loginLog.changeUserInfo(0, "-"));

    String address = ip2AddressService.getAddress(cmd.getIp());
    loginLog.changeDevice(cmd.getBrowser(), cmd.getOs(), cmd.getIp(), address);
  }
}
